package it.polimi.swKnights.SWIMv2.servlets.login;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerRemote;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Admin;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.RegisteredUser;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.annotation.security.DeclareRoles;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginController
 */
@DeclareRoles("RegisteredUser")
public class LoginController extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String userName = request.getParameter("username");
		String password = request.getParameter("password");

		LoginHandlerRemote loginBean = this.lookUp(LoginHandlerRemote.class); //guest logged admin

		try
		{
			String destination = "./userHome?wellcome=true&user="+userName;
			loginBean.checkLoginData(userName, password);

			HttpSession session = request.getSession();
			session.setAttribute("userName", userName);
			session.setAttribute("password", password);

			if(loginBean.hasPrivileges(userName, Admin.class))
			{
				session.setAttribute("user_type","admin");
			}
			else if(loginBean.hasPrivileges(userName, RegisteredUser.class))
			{
				session.setAttribute("user_type", "logged");
			} 
			
			response.sendRedirect(destination);

		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error="+Errors.invalidlogin);
		}
		
		

	}

}
